package com.ds.infra.rpc.autoconfigure.scanner;

import com.ds.infra.rpc.annotation.RpcReference;
import com.ds.infra.rpc.registry.service.ServiceDiscovery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * 作用：RPC引用扫描器V1实现
 *
 * @author WeiShaoying
 */
// @Slf4j
// public class RpcReferenceScannerV1 implements BeanPostProcessor {
//
//     @Autowired
//     private ServiceDiscovery serviceDiscovery;
//
//     @Autowired
//     private ApplicationContext applicationContext;
//
//     @Override
//     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//         Class<?> targetClass = bean.getClass();
//         ReflectionUtils.doWithFields(targetClass, field -> {
//             RpcReference rpcReference = AnnotationUtils.getAnnotation(field, RpcReference.class);
//             if (rpcReference != null) {
//                 injectProxy(bean, field, rpcReference);
//             }
//         });
//         return bean;
//     }
//
//     private void injectProxy(Object bean, Field field, RpcReference rpcReference) {
//         try {
//             Class<?> interfaceClass = field.getType();
//             if (!interfaceClass.isInterface()) {
//                 throw new IllegalArgumentException("@RpcReference can only be used on interface fields");
//             }
//
//             // 创建动态代理
//             RpcClientProxy proxy = new RpcClientProxy(
//                 // interfaceClass,
//                 rpcReference.version(),
//                 serviceDiscovery,
//                 rpcReference.loadBalance(),
//                 rpcReference.timeout(),
//                 rpcReference.retries()
//             );
//
//             Object clientProxy = proxy.getProxy();
//             field.setAccessible(true);
//             field.set(bean, clientProxy);
//             log.info("Injected RPC proxy for {}#{}", bean.getClass().getSimpleName(), field.getName());
//         } catch (Exception e) {
//             throw new BeanCreationException("Failed to inject RPC proxy for field " + field.getName(), e);
//         }
//     }
// }
